<!--
 * @Description: 储值套餐
 * @Author: DXV-RGWU-TUFH-RFCY-IEGMYY
 * @Date: 2021-07-04 13:17:22
 * @LastEditTime: 2023-05-26 18:44:09
 * @LastEditors: DXV-RGWU-TUFH-RFCY-IEGMYY
-->

<template>
  <div class="lb-appclass-classroom-list">
    <top-nav />
    <div class="page-main">
      <el-row class="page-top-operate">
        <lb-button
          size="medium"
          type="primary"
          icon="el-icon-plus"
          @click="toShowDialog('sub')"
          v-hasPermi="`${$route.name}-add`"
          >{{ $t('menu.FinanceStoredAdd') }}</lb-button
        >
      </el-row>
      <el-table
        v-loading="loading.list"
        :data="tableData.list"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        tooltip-effect="dark"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" fixed> </el-table-column>
        <el-table-column prop="title" label="套餐名称" min-width="200">
        </el-table-column>
        <el-table-column prop="price" label="购买价格" min-width="120">
          <template slot-scope="scope"> ¥{{ scope.row.price }} </template>
        </el-table-column>
        <el-table-column prop="true_price" label="实际充值" min-width="120">
          <template slot-scope="scope"> ¥{{ scope.row.true_price }} </template>
        </el-table-column>
        <el-table-column prop="top" label="排序值"> </el-table-column>
        <el-table-column prop="create_time" label="创建时间" min-width="120">
          <template slot-scope="scope">
            <p>{{ scope.row.create_time | handleTime(1) }}</p>
            <p>{{ scope.row.create_time | handleTime(2) }}</p>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="是否上架">
          <template slot-scope="scope">
            <el-switch
              :disabled="
                $route.meta.pagePermission[0].auth.includes('edit')
                  ? false
                  : true
              "
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="updateItem(scope.row.id, scope.row.status)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="140">
          <template slot-scope="scope">
            <div class="table-operate">
              <lb-button
                size="mini"
                plain
                type="primary"
                @click="toShowDialog('sub', scope.row)"
                v-hasPermi="`${$route.name}-edit`"
                >{{ $t('action.edit') }}</lb-button
              >
              <lb-button
                size="mini"
                plain
                type="danger"
                @click="confirmDel(scope.row.id)"
                v-hasPermi="`${$route.name}-delete`"
                >{{ $t('action.delete') }}</lb-button
              >
              <lb-button
                size="mini"
                plain
                type="success"
                @click="toShowDialog('pay', scope.row)"
                v-hasPermi="`${$route.name}-payBalanceOrder`"
                v-show="scope.row.status == 1"
                >{{ $t('action.payBalanceOrder') }}</lb-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>

      <lb-page
        :batch="false"
        :page="searchForm.list.page"
        :pageSize="searchForm.list.limit"
        :total="total.list"
        @handleSizeChange="handleSizeChange($event, 'list')"
        @handleCurrentChange="handleCurrentChange($event, 'list')"
      >
      </lb-page>

      <el-dialog
        :title="
          $t(subForm.id ? 'menu.FinanceStoredEdit' : 'menu.FinanceStoredAdd')
        "
        :visible.sync="showDialog.sub"
        width="500px"
        center
      >
        <el-form
          class="dialog-form"
          :model="subForm"
          ref="subForm"
          :rules="subFormRules"
          label-width="100px"
        >
          <el-form-item label="套餐名称" prop="title">
            <el-input
              v-model="subForm.title"
              maxlength="20"
              show-word-limit
              placeholder="请输入套餐名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="购买价格" prop="price">
            <el-input-number
              class="lb-input-number"
              :min="0.01"
              :precision="2"
              :controls="false"
              v-model="subForm.price"
              placeholder="请输入购买价格"
            ></el-input-number>
            <lb-tool-tips>用户所要支付的价格</lb-tool-tips>
          </el-form-item>
          <el-form-item label="实际充值" prop="true_price">
            <el-input
              v-model="subForm.true_price"
              placeholder="请输入实际充值"
            ></el-input>
            <lb-tool-tips>实际充入会员卡的价格</lb-tool-tips>
          </el-form-item>
          <el-form-item label="排序值" prop="top">
            <el-input-number
              class="lb-input-number"
              :min="0"
              :controls="false"
              v-model="subForm.top"
              placeholder="请输入排序值"
            ></el-input-number>
            <lb-tool-tips>值越大, 排序越靠前</lb-tool-tips>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDialog.sub = false">取 消</el-button>
          <el-button
            type="primary"
            @click="submitFormInfo('sub')"
            v-preventReClick
            >确 定</el-button
          >
        </span>
      </el-dialog>

      <el-dialog
        :title="$t('action.payBalanceOrder')"
        :visible.sync="showDialog.pay"
        width="800px"
        center
      >
        <el-form
          class="dialog-form"
          :model="payForm"
          ref="payForm"
          :rules="payFormRules"
          label-width="100px"
        >
          <el-form-item label="储值套餐名称" prop="">
            {{ payForm.title }}
          </el-form-item>
          <el-form-item label="购买价格" prop="">
            ¥{{ payForm.price }}
          </el-form-item>
          <el-form-item label="实际充值" prop="">
            ¥{{ payForm.true_price }}
          </el-form-item>
          <el-form-item label="充值用户" prop="user">
            <lb-button
              type="primary"
              icon="el-icon-plus"
              @click="toShowDialog('user')"
              >选择充值用户</lb-button
            >
            <el-table
              :data="payForm.user"
              :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
              class="mt-lg"
              style="width: 100%"
            >
              <el-table-column prop="id" label="ID"></el-table-column>
              <el-table-column
                prop="nickName"
                label="微信昵称"
              ></el-table-column>
              <el-table-column prop="avatarUrl" label="微信头像">
                <template slot-scope="scope">
                  <lb-image :src="scope.row.avatarUrl" />
                </template>
              </el-table-column>
              <el-table-column prop="phone" label="手机号"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <div class="table-operate">
                    <lb-button
                      size="mini"
                      plain
                      type="danger"
                      @click="toDel(scope.row.id)"
                      >{{ $t('action.delete') }}</lb-button
                    >
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDialog.pay = false">取 消</el-button>
          <el-button
            type="primary"
            @click="submitFormInfo('pay')"
            v-preventReClick
            >确 定</el-button
          >
        </span>
      </el-dialog>

      <el-dialog
        title="选择充值用户"
        :visible.sync="showDialog.user"
        width="800px"
        center
      >
        <el-form
          :inline="true"
          :model="searchForm.user"
          ref="userForm"
          label-width="70px"
        >
          <el-form-item label="输入查询" prop="nickName">
            <el-input
              v-model="searchForm.user.nickName"
              placeholder="请输入微信昵称/手机号"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <lb-button
              size="medium"
              type="primary"
              icon="el-icon-search"
              style="margin-right: 5px"
              @click="getTableDataList(1, 'user')"
              >{{ $t('action.search') }}</lb-button
            >
            <lb-button
              size="medium"
              icon="el-icon-refresh-left"
              style="margin-right: 5px"
              @click="resetForm('user')"
              >{{ $t('action.reset') }}</lb-button
            >
          </el-form-item>
        </el-form>
        <el-table
          :data="tableData.user"
          ref="multipleTable"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="id" label="ID"></el-table-column>
          <el-table-column prop="nickName" label="微信昵称"></el-table-column>
          <el-table-column prop="avatarUrl" label="微信头像">
            <template slot-scope="scope">
              <lb-image :src="scope.row.avatarUrl" />
            </template>
          </el-table-column>
          <el-table-column prop="phone" label="手机号"></el-table-column>
        </el-table>
        <lb-page
          :batch="false"
          :page="searchForm.user.page"
          :pageSize="searchForm.user.limit"
          :total="total.user"
          @handleSizeChange="handleSizeChange($event, 'user')"
          @handleCurrentChange="handleCurrentChange($event, 'user')"
        >
        </lb-page>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDialog.user = false">取 消</el-button>
          <el-button type="primary" @click="handleDialogConfirm"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
export default {
  components: {},
  data () {
    let validatePrice = (rule, value, callback) => {
      if (!/^(([0-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/.test(value)) {
        callback(new Error('请输入正确的金额，最多保留两位小数'))
      } else {
        callback()
      }
    }
    return {
      loading: { list: false, user: false },
      searchForm: {
        list: {
          page: 1,
          limit: 10
        },
        user: {
          page: 1,
          limit: 10,
          nickName: ''
        }
      },
      tableData: { list: [], user: [] },
      total: { list: 0, user: 0 },
      showDialog: { sub: false, pay: false, user: false },
      multipleSelection: [],
      subForm: {
        id: '',
        title: '',
        price: '',
        true_price: '',
        top: 0
      },
      subFormRules: {
        title: { required: true, validator: this.$reg.isNotNull, text: '套餐名称', reg_type: 2, trigger: 'blur' },
        price: { required: true, validator: validatePrice, trigger: 'blur' },
        true_price: { required: true, validator: validatePrice, trigger: 'blur' },
        top: { required: true, type: 'number', message: '请输入排序值', trigger: 'blur' }
      },
      payForm: {
        id: '',
        title: '',
        price: '',
        true_price: '',
        user: []
      },
      payFormRules: {
        user: { required: true, type: 'array', message: '请选择充值用户', trigger: 'blur' }
      }
    }
  },
  async created () {
    this.getTableDataList(1, 'list')
  },
  methods: {
    resetForm (form) {
      let name = `${form}Form`
      this.$refs[name].resetFields()
      this.getTableDataList(1, form)
    },
    handleSizeChange (val, key) {
      this.searchForm[key].limit = val
      this.handleCurrentChange(1, key)
    },
    handleCurrentChange (val, key) {
      this.searchForm[key].page = val
      this.getTableDataList('', key)
    },
    /**
     * @method 获取列表
     */
    async getTableDataList (flag, key) {
      if (flag) this.searchForm[key].page = 1
      this.loading[key] = true
      let searchForm = JSON.parse(JSON.stringify(this.searchForm[key]))
      let methodArr = {
        list: { methodKey: 'finance', methodModel: 'cardList' },
        user: { methodKey: 'custom', methodModel: 'userList' }
      }
      let { methodKey, methodModel } = methodArr[key]
      let { code, data } = await this.$api[methodKey][methodModel](searchForm)
      this.loading[key] = false
      if (code !== 200) return
      this.tableData[key] = data.data
      this.total[key] = data.total
    },
    /**
     * @method: 删除
     * @param {*} id
     */
    confirmDel (id) {
      this.$confirm(this.$t('tips.confirmDelete'), this.$t('tips.reminder'), {
        confirmButtonText: this.$t('action.comfirm'),
        cancelButtonText: this.$t('action.cancel'),
        type: 'warning'
      }).then(() => {
        this.updateItem(id, -1)
      })
    },
    /**
     * @method: 上下架
     */
    async updateItem (id, status) {
      this.$api.finance.cardUpdate({ id, status }).then(res => {
        if (res.code === 200) {
          this.$message.success(this.$t(status === -1 ? 'tips.successDel' : 'tips.successOper'))
          if (status !== -1) return
          this.searchForm.list.page = this.searchForm.list.page < Math.ceil((this.total.list - 1) / this.searchForm.list.limit) ? this.searchForm.list.page : Math.ceil((this.total.list - 1) / this.searchForm.list.limit)
          this.getTableDataList('', 'list')
        } else {
          if (status === -1) return
          this.getTableDataList('', 'list')
        }
      })
    },
    async toShowDialog (key, item = {}) {
      item = JSON.parse(JSON.stringify(item))
      if (key !== 'user') {
        if (key === 'pay') {
          item.user = []
        }
        for (let i in this[`${key}Form`]) {
          this[`${key}Form`][i] = item[i]
        }
      } else {
        this.searchForm.user.nickName = ''
        await this.getTableDataList(1, key)
      }
      this.showDialog[key] = !this.showDialog[key]
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    handleDialogConfirm () {
      let user = JSON.parse(JSON.stringify(this.payForm.user))
      let arr1 = user.length > 0 ? user.map(item => { return item.id }) : []
      this.multipleSelection.map(item => {
        if (arr1.includes(item.id)) return
        user.push(item)
      })
      this.payForm.user = user
      this.showDialog.user = false
    },
    toDel (id) {
      let index = this.payForm.user.findIndex(item => {
        return item.id === id
      })
      this.payForm.user.splice(index, 1)
    },
    async submitFormInfo (key) {
      let flag = true
      this.$refs[`${key}Form`].validate(valid => {
        if (!valid) flag = false
      })
      if (flag) {
        let subForm = JSON.parse(JSON.stringify(this[`${key}Form`]))
        if (key === 'pay') {
          let arr = subForm.user.map(item => {
            return item.id
          })
          if (arr.length > 50) {
            this.$message.error(`所选充值用户超过50位，请重新选择！`)
            return
          }
          let { id } = subForm
          subForm = { card_id: id, user_id: arr }
        }
        let methodModel = key === 'pay' ? 'payBalanceOrder' : subForm.id ? 'cardUpdate' : 'cardAdd'
        let { code } = await this.$api.finance[methodModel](subForm)
        if (code !== 200) return
        this.$message.success(this.$t(key === 'sub' && subForm.id ? 'tips.successRev' : 'tips.successSub'))
        this.showDialog[key] = false
        this.getTableDataList('', 'list')
      }
    }
  },
  filters: {
    handleTime (val, type) {
      let time = type === 1 ? moment(val * 1000).format('YYYY-MM-DD') : type === 2 ? moment(val * 1000).format('HH:mm:ss') : moment(val * 1000).format('YYYY-MM-DD HH:mm:ss')
      return time
    }
  }
}
</script>

<style lang="scss" scoped>
.lb-appclass-classroom-list {
  width: 100%;
  .page-main {
    width: 100%;
    .el-input,
    .el-select,
    .el-input-number {
      width: 200px;
    }
    .dialog-form {
      .el-input,
      .el-select,
      .el-input-number {
        width: 300px;
      }
    }
  }
}
</style>
